<?php

/**
 * 订单模型管理
 * @author cjli
 *
 */
class OrderModel extends Model
{
    /**
     * 订单状态
     */
    const ORDER_UNCONFIRMED = 0; //未确认
    const ORDER_CONFIRMED = 1; //已确认
    const ORDER_COMPLETE = 2; //已完成
    const ORDER_CANCELED = -1; //取消
    const ORDER_DEL = -2; //已删除
    const ORDER_PAUSED = -3; //已暂停

    /**
     * 支付状态
     */
    const PAY_UNPAYED = 0;//未支付
    const PAY_PAYED = 1; //已支付
    const PAY_PARTIAL_REFUND = 2; //部分退款
    const PAY_FULL_REFUND = 3;//全部退款
    const PAY_FOUR_REFUND = 4;//已支付定金
    const PAY_PAYED_IN = 5; //支付中

    /**
     * 配送状态
     */
    const SHIPPING_UNSHIPPED = 0; //未发货
    const SHIPPING_SHIPPED = 1; //已发货
    const SHIPPING_RECEIVED = 2; //收货确认
    const SHIPPING_SHIPPED_PART = 3; //已发货(部分商品)
    const SHIPPING_RETURNED = 4; //退货

    static $orderStatus = array(
        self::ORDER_UNCONFIRMED => '_ORDER_UNCONFIRMED_',
        self::ORDER_CONFIRMED => '_ORDER_CONFIRMED_',
        self::ORDER_COMPLETE => '_ORDER_COMPLETE_',
        self::ORDER_CANCELED => '_ORDER_CANCEL_',
//    self::ORDER_DEL => '_ORDER_DELETE_',
        self::ORDER_PAUSED => '_ORDER_PAUSED_',
    );

    static $paymentStatus = array(
        self::PAY_UNPAYED => '_PAY_UNPAYED_',
        self::PAY_PAYED => '_PAY_PAYED_',
        self::PAY_PARTIAL_REFUND => '_PAY_PARTIAL_REFUND_',
        self::PAY_FULL_REFUND => '_PAY_FULL_REFUND_',
        self::PAY_FOUR_REFUND => '_PAY_FOUR_REFUND_',
        //self::PAY_PAYED_IN => '__PAY_PAYED_IN_'
    );
    static $shippingStatus = array(
        self::SHIPPING_UNSHIPPED => '_SHIPPING_UNSHIPPED_',
        self::SHIPPING_SHIPPED => '_SHIPPING_SHIPPED_',
        self::SHIPPING_RECEIVED => '_SHIPPING_RECEIVED_',
        self::SHIPPING_SHIPPED_PART => '_SHIPPING_SHIPPED_PART_',
        self::SHIPPING_RETURNED => '_SHIPPING_RETURND_'
    );
    static $giftshippingStatus = array(
        self::SHIPPING_UNSHIPPED => '_GIFT_SHIPPING_UNSHIPPED_',
        self::SHIPPING_SHIPPED => '_GIFT_SHIPPING_SHIPPED_',
        self::SHIPPING_RECEIVED => '_GIFT_SHIPPING_RECEIVED_',
        self::SHIPPING_SHIPPED_PART => '_GIFT_SHIPPING_SHIPPED_PART_',
        self::SHIPPING_RETURNED => '_GIFT_SHIPPING_RETURND_'
    );

    static $deliveryStatus = array(
        '1' => '_DELIVERY_ALLOCATION_', //配货
        '2' => '_DELIVERY_DELIVERED_', //已发货
//  	'3' => '取消',
//  	'4' => '退货',
    );
    static $purchaseType = array(
        '1' => '_PURCHASE_RETURNED_',
        '2' => '_PURCHASE_EXCHANGE_',
        '3' => '_PURCHASE_SERVICE_',
        '4' => '_PURCHASE_REFUND_',
    );

    static $purchaseStatus = array(
        '1' => '_WAITING_PROCESS_',
        '2' => '_WAITING_CUSTOMER_COMFIRM_',
        '3' => '_PURCHASE_RESOLVED_',
        '4' => '_PURCHASE_CANCAL_'
    );

    /**
     * 获取订单关联产品列表
     * @param int $order_id 订单ID
     * @return array
     */
    public static function get_order_product_list($order_id)
    {
        global $language_id;

        $order_item_db = D('orders_items');
        $order_item_db->field('orders_items.*,product.small_img,product.refund,product.yushou_end_time,product.weikuan_time,product.yufu_price,product.catid,product.model_id');
        $order_item_db->join('product ON product.id = orders_items.product_id');
        $order_item_db->where(array('order_id' => $order_id));
        $productList = $order_item_db->select();
        if ($productList) {
            foreach ($productList as &$product) {
                $product['goods_dingjin'] = $product['qty'] * $product['yufu_price'];

                if ($product['attr']) {
                    $data = unserialize($product['attr']);
                    $product['original_attr'] = array();
                    if ($data) {
                        $attributes = array();
                        if ($product['custom_type']) {
                            foreach ($data as $vk => $val) {
                                $attributes[] = $val['attr_name'] . ':' . $val['attr_value'];
                                //放入原先跟购物车里一样的attr数据
                                $attrStr = $val['attr_id'] . ':' . $val['attr_name'] . ':' . $val['product_attr_id'] . ':' . $val['attr_value'];
                                if ($val['product_attr_id'] != '') {
                                    $attrStr .= ':' . $val['attr_value_id'];
                                }
                                if (in_array($val['attr_id'], array(54, 70, 112, 134))) {
                                    $product['original_attr'][$val['attr_value_id']] = $attrStr;
                                } else {
                                    $product['original_attr'][$val['attr_id']] = $attrStr;
                                }

                            }
                        } else {
                            foreach ($data as $vk => $val) {
                                $attributes[] = $vk . ':' . $val;
                            }
                        }
                        $attribute = implode(' , ', $attributes);
                    }
                    $product['attr'] = $attribute;
                }
                $cacheId = 'product_' . $product['product_id'] . '_' . $language_id;
                $cache = S($cacheId);
                if (!$cache) {
                    $cache = ProductModel::get_product_info($product['product_id'], $language_id);
                }
                $product['url'] = $cache['url'];
                $product['name'] = $cache['name'];
            }
            unset($product);
        }
        return $productList;
    }

    /**
     * 获取订单信息
     * @param int $order_id 订单ID
     * @return array
     */
    public static function get_order_info($order_id)
    {
        $order_db = D('orders');
        $orderInfo = $order_db->find($order_id);
        $paymentInfo = PaymentModel::get_payment_info($orderInfo['payment_method']);
        //dump($paymentInfo);exit;
        $shippingInfo = ShippingModel::get_shipping_info_by_name($orderInfo['shipping_method']);
        $orderInfo['payment_method_name'] = $paymentInfo['title'];
        $orderInfo['shipping_method_name'] = $shippingInfo['title'];
        $orderInfo['shippingInfo'] = $shippingInfo;
        $orderInfo['paymentInfo'] = $paymentInfo;
        return $orderInfo;
    }

    /**
     * 获取订单信息
     * @param int $order_sn 订单号
     * @return array
     */
    public static function get_oreder_info_by_order_sn($order_sn)
    {
        $order_db = D('orders');
        $order_id = $order_db->where(array('order_sn' => $order_sn))->getField('id');
        if ($order_id) {
            $orderInfo = self::get_order_info($order_id);
        }
        return $orderInfo ? $orderInfo : null;
    }


    /**
     * 添加订单
     * @return int 订单ID号
     */
    public static function insert_order($post)
    {
        global $user, $language_id;
        $order_db = D('orders');
        $post['delivery_cid'] = intval($post['delivery_cid']);
        $hongbao_id = intval($post['hongbao_id']);
        $coupon_code = $post['coupon_code'];
        $post['delivery_pid'] = intval($post['delivery_pid']);
        $product_amount = isset($post['product_amount']) ? floatval($post['product_amount']) : (isset($post['goods_amount']) ? floatval($post['goods_amount']) : 0);
        $payment_fee = isset($post['payment_fee']) ? floatval($post['payment_fee']) : 0;
        $shipping_fee = isset($post['shipping_fee']) ? floatval($post['shipping_fee']) : 0;
        $surplus_money = isset($post['surplus_money']) ? floatval($post['surplus_money']) : 0;
        $integral_money = 0;
        $hongbao_money = isset($post['hongbao_money']) ? floatval($post['hongbao_money']) : 0;
        $coupon_money = isset($post['coupon_money']) ? floatval($post['coupon_money']) : 0;
        //如果使用余额小于会员余额
        if ($user && isset($user['user_money']) && $user['user_money'] > 0) {
            $surplus_money = $user['user_money'] < $surplus_money ? $user['user_money'] : $surplus_money;
        } else {
            $surplus_money = 0;
        }
        $currency = isset($_SESSION['currency']) ? $_SESSION['currency'] : C('currency');
        $order_sn = self::get_order_sn();
        $shippingInfo = ShippingModel::get_shipping_info_by_name($post['shipping_method']);
        $data = array(
            'user_id' => isset($user['id']) ? $user['id'] : 0,
            'order_sn' => $order_sn,
            'order_status' => OrderModel::ORDER_UNCONFIRMED,
            'payment_status' => OrderModel::PAY_UNPAYED,
            'shipping_status' => OrderModel::SHIPPING_UNSHIPPED,
            'payment_method' => $post['payment_method'],
            'shipping_method' => $post['shipping_method'],
            'shipping_id' => $shippingInfo['id'],
            'delivery_first_name' => trim($post['delivery_first_name']),
            'delivery_last_name' => trim($post['delivery_last_name']),
            'delivery_phone' => isset($post['delivery_phone']) ? trim($post['delivery_phone']) : null,
            'delivery_mobile' => isset($post['delivery_mobile']) ? trim($post['delivery_mobile']) : null,
            'delivery_postcode' => isset($post['delivery_postcode']) ? trim($post['delivery_postcode']) : null,
            'delivery_email' => isset($post['delivery_email']) ? trim($post['delivery_email']) : null,
            'delivery_cid' => $post['delivery_cid'],
            'delivery_pid' => $post['delivery_pid'],
            'delivery_province' => isset($post['delivery_province']) ? trim($post['delivery_province']) : null,
            'delivery_city' => isset($post['delivery_city']) ? trim($post['delivery_city']) : null,
            'delivery_address' => isset($post['delivery_address']) ? trim($post['delivery_address']) : null,
            'delivery_address2' => isset($post['delivery_address2']) ? trim($post['delivery_address2']) : null,
            'delivery_address3' => isset($post['delivery_address3']) ? trim($post['delivery_address3']) : null,
            'delivery2_first_name' => isset($post['delivery2_first_name']) && $post['delivery2_first_name'] ? trim($post['delivery2_first_name']) : null,
            'delivery2_last_name' => isset($post['delivery2_last_name']) && $post['delivery2_last_name'] ? trim($post['delivery2_last_name']) : null,
            'delivery2_phone' => isset($post['delivery2_phone']) ? trim($post['delivery2_phone']) : null,
            'delivery2_mobile' => isset($post['delivery2_mobile']) ? trim($post['delivery2_mobile']) : null,
            'delivery2_postcode' => isset($post['delivery2_postcode']) ? trim($post['delivery2_postcode']) : null,
            'delivery2_email' => isset($post['delivery2_email']) ? trim($post['delivery2_email']) : null,
            'delivery2_cid' => isset($post['delivery2_cid']) ? $post['delivery2_cid'] : 0,
            'delivery2_province' => isset($post['delivery2_province']) ? trim($post['delivery2_province']) : null,
            'delivery2_city' => isset($post['delivery2_city']) ? trim($post['delivery2_city']) : null,
            'delivery2_address' => isset($post['delivery2_address']) ? trim($post['delivery2_address']) : null,
            'delivery2_address2' => isset($post['delivery2_address2']) ? trim($post['delivery2_address2']) : null,
            'delivery2_address3' => isset($post['delivery2_address3']) ? trim($post['delivery2_address3']) : null,
            'data' => isset($post['data']) && $post['data'] ? serialize($post['data']) : null,
            'remark' => ($post['remark']),
            'payment_fee' => $payment_fee,
            'shipping_fee' => $shipping_fee,
            'product_amount' => $product_amount,
            'surplus_money' => $surplus_money,
            'integral' => isset($post['integral']) ? intval($post['integral']) : 0,
            'integral_money' => $integral_money,
            'hongbao_money' => $hongbao_money,
            'coupon_code' => $coupon_code,
            'coupon_money' => $coupon_money,
            'start_time' => time(),
            'stockout' => intval($post['stockout']),
            'language_id' => $language_id,
            'currency' => $currency,
            'measure_data' => isset($post['measure_data']) && $post['measure_data'] ? serialize($post['measure_data']) : null,
            'address_id' => intval($post['address_id']) > 0 ? intval($post['address_id']) : 0,
            'is_mobile' => intval($post['is_mobile']) ? intval($post['is_mobile']) : 0,
            'class_id' => intval($post['class_id']) ? intval($post['class_id']) : 0,
            'is_gift_orders' => intval($post['is_gift_orders']) ? intval($post['is_gift_orders']) : 0,
            'client_note' => isset($post['client_note']) ? trim($post['client_note']) : null,
        );

        //订单总费用
        $order_amount = $product_amount + $payment_fee + $shipping_fee - $hongbao_money;
        $data['order_amount'] = $order_amount;

        //应付费用
        $pay_amount = $order_amount - $surplus_money - $integral_money;
        $data['pay_amount'] = $pay_amount;

        //更新国家
        if ($post['delivery_cid']) {
            $area_info = SiteModel::get_region_info($post['delivery_cid']);
            if ($area_info) {
                $data['delivery_country'] = $area_info['name'];
            }
        } else {
            //国家为空的话，订单不能成功
            return false;
        }
        if ($data['delivery2_cid']) {
            $area_info = SiteModel::get_region_info($data['delivery2_cid']);
            if ($area_info) {
                $data['delivery2_country'] = $area_info['name'];
            }
        }
        //更新省市
        if ($post['delivery_pid']) {
            $area_info = SiteModel::get_region_info($post['delivery_pid']);
            if ($area_info) {
                $data['delivery_province'] = $area_info['name'];
            }
        }

        $order_id = $order_db->add($data);
//  	echo $order_db->getLastSql();exit;
        if ($order_id) {
            //扣除会员的余额
            if ($surplus_money && $data['user_id']) {
                UserModel::log_account_change($data['user_id'], (-1) * $surplus_money, 0, 0, 0, L('_ORDER_USE_BALANCE_PAYMENT_') . ' ' . L('_THE_ORDER_NUMBER_IS_') . ' ' . $order_sn, UserModel::ACT_PAY);
            }
            //删除相应的红包
            if ($hongbao_id > 0) {

                $user_bonus_db = D('user_bonus');
                $data02 = array(
                    'bonus_sn' => $order_sn,
                    'used_time' => time(),
                );
                $user_bonus_db->where('id=' . $hongbao_id)->save($data02);


                $bonus_db = D('bonus_type');
                $bonusInfo = $bonus_db->field('id,min_amount,send_start_date,send_end_date')->where('send_type=1')->find();
                //判断红包是否在发送期间
                if (time() >= $bonusInfo['send_start_date'] && time() <= $bonusInfo['send_end_date']) {
                    if ($order_amount > $bonusInfo['min_amount']) {
                        $data = array(
                            'bonus_id' => intval($bonusInfo['id']),
                            'bonus_sn' => 0,
                            'user_id' => intval($user['id']),
                            'used_time' => 0,
                            'order_id' => 0,
                            'emailed' => 0,//1：已发成功；0未成功
                            'time' => time(),
                        );
                        $user_bonus_id = $user_bonus_db->add($data);
                    }
                }
            }
        }
        return $order_id;
    }

    /**
     * 更新订单
     * @param int $oid 订单ID
     * @return boolean
     */
    public static function update_order($oid, $post)
    {
        $order_db = D('orders');
        $post['delivery_cid'] = intval($post['delivery_cid']);
        $post['delivery_pid'] = intval($post['delivery_pid']);

        $shippingInfo = ShippingModel::get_shipping_info_by_name($post['shipping_method']);
        $data = array(
            'order_status' => intval($post['order_status']),
            'payment_status' => intval($post['payment_status']),
            'shipping_status' => intval($post['shipping_status']),
            'payment_method' => $post['payment_method'],
            'shipping_id' => $shippingInfo['id'],
            'shipping_method' => $post['shipping_method'],
            //'payment_fee' => floatval($post['payment_fee']),
            'shipping_fee' => floatval($post['shipping_fee']),
            'shipping_no' => $post['shipping_no'] ? trim($post['shipping_no']) : null,
            'delivery_first_name' => trim($post['delivery_first_name']),
            'delivery_last_name' => trim($post['delivery_last_name']),
            'delivery_phone' => trim($post['delivery_phone']),
            'delivery_mobile' => trim($post['delivery_mobile']),
            'delivery_email' => trim($post['delivery_email']),
            'delivery_postcode' => trim($post['delivery_postcode']),
            'delivery_cid' => $post['delivery_cid'],
            'delivery_pid' => $post['delivery_pid'],
            'delivery_province' => isset($post['delivery_province']) ? trim($post['delivery_province']) : null,
            'delivery_city' => isset($post['delivery_city']) ? trim($post['delivery_city']) : null,
            'delivery_address' => isset($post['delivery_address']) ? trim($post['delivery_address']) : null,
            'delivery_address2' => isset($post['delivery_address2']) ? trim($post['delivery_address2']) : null,
            'delivery_address3' => isset($post['delivery_address3']) ? trim($post['delivery_address3']) : null,
            'delivery_time' => ($post['delivery_time']),
            'data' => isset($post['data']) && $post['data'] ? serialize($post['data']) : null,
            'stockout' => intval($post['stockout']),
            'language_id' => $language_id,
            'currency' => $_SESSION['currency'],
        );
        if ($post['product_amount']) {
            $data['product_amount'] = $post['product_amount'];
        }
        if ($post['order_amount']) {
            $data['order_amount'] = $post['order_amount'];
        }
        //更新国家
        if ($post['delivery_cid']) {
            $area_info = SiteModel::get_region_info($post['delivery_cid']);
            if ($area_info) {
                $data['delivery_country'] = $area_info['name'];
            }
        }
        //更新省市
        if ($post['delivery_pid']) {
            $area_info = SiteModel::get_region_info($post['delivery_pid']);
            if ($area_info) {
                $data['delivery_province'] = $area_info['name'];
            }
        }

        $result = $order_db->where(array('id' => $oid))->save($data);

        self::update_order_prices($oid);
        //self::update_order_prices02($oid);
        return (boolean)$result;
    }

    /**
     *
     * 更新订单状状态
     * @param int $order_id
     * @param array $post post数据
     * @return boolean
     */


    public function update_order_status($order_id, $post)
    {
        $set = array(
            'order_status' => isset($post['order_status']) ? $post['order_status'] : null,
            'payment_status' => isset($post['payment_status']) ? $post['payment_status'] : null,
            'shipping_status' => isset($post['shipping_status']) ? $post['shipping_status'] : null,
        );
        foreach ($set as $key => $val) {
            if (is_null($val)) {
                unset($set[$key]);
            }
        }
        if (empty($set)) return false;

        if (isset($set['order_status']) && $set['order_status'] == self::ORDER_CONFIRMED) {
            $set['confirm_time'] = time();
        } else {
            $set['update_time'] = time();
        }
        if (isset($set['payment_status']) && $set['payment_status'] == self::PAY_PAYED) {
            $set['payment_time'] = time();
        }

        $order_db = D('orders');
        $affected = $order_db->where(array('id' => $order_id))->save($set);

        if (C('invite_switch') && $set['payment_time']) { //好友邀请活动的返现
            self::invite_fanxian($order_id);
        }
        if ($set['payment_time']) {
            self::gift_email($order_id);//giftcard 发送邮件
            self::return_fabrics_kit($order_id);//面料卡返现
        }
        return (boolean)$affected;
    }

    public static function return_fabrics_kit($order_id)
    {
        $info = M('orders')->field('orders.user_id,orders.shipping_fee,orders.order_amount,orders.pay_amount,orders_items.product_id,orders_items.pay_price')
            ->join('left join orders_items on orders.id=orders_items.order_id')->where('orders.id=' . $order_id)->select();
        if (!$info) {
            return;
        }
        foreach ($info as $k => $v) {
            if ($v['product_id'] == 505 && $v['user_id']) {
                $amount_db = M('user_account');//记录充值日志
                $user_amount_data['user_id'] = $v['user_id'];
                $user_amount_data['add_time'] = time();
                $user_amount_data['paid_time'] = time();
                $user_amount_data['admin_note'] = '_Fabric_Swatches_';
                $user_amount_data['amount'] = 99;
                $user_amount_data['process_type'] = 0; //类型为充值
                $user_amount_data['is_paid'] = 1; //已完成支付
                //$user_amount_data['user_note'] = $code;
                $amount_db->add($user_amount_data);
                UserModel::log_account_change($v['user_id'], $user_amount_data['amount'], 0, 0, 0, L('_Fabric_Swatches_'), UserModel::ACT_SAVING);
                //break;
            }
        }
    }

    public static function gift_email($order_id, $email_obj = null)
    {
        $info = M('orders_items as a ')->field('a.id,a.attr,a.qty,b.custom_price')->join('left join product as b on a.product_id = b.id')->where("a.order_id=$order_id and catid = 2121")->select();

        if (!$info) {
            return;
        }
        if ($email_obj) {
            $mailInstance = $email_obj;
        } else {
            $mailInstance = new EmailModel();
        }
        foreach ($info as $k => $v) {
            $attr = unserialize($v['attr']);
            $email_template = UserModel::get_email_template_info('giftcard', $attr['language_id']);
            $coupon_template = UserModel::get_email_template_info('couponEmail', $attr['language_id']);//黑色星期五活动充值送优惠码邮件
            $gift_code_arr = array();
            for ($i = 1; $i <= $v['qty']; $i++) {
                $data['to_name'] = $attr['to_name'];
                $data['from_name'] = $attr['from_name'];
                $data['amount'] = $v['custom_price'];
                $data['recipient_email'] = $attr['recipient_email'];
                $data['language_id'] = $attr['language_id'] ? $attr['language_id'] : 1;
                $data['user_email'] = $attr['user_email'];
                $data['is_pay'] = 1;
                $data['msg'] = $attr['msg'] ? $attr['msg'] : '';
                $data['gift_code'] = 'GIFT' . strtoupper(substr(uniqid(), -8));
                $gift_code_arr[] = $data['gift_code'];
                $data['order_id'] = $order_id;

                if (C('coupon_email_switch')) {//黑色星期五活动充值送优惠码
                    $data2['coupon_code'] = 'ONLY' . substr(uniqid(), -7);
                    $data2['coupon_money'] = $v['custom_price'];
                    $data2['max_amount'] = 1000000;
                    $data2['min_amount'] = 5;  //基本没有使用限制
                    $data2['start_time'] = 1417103940;//优惠卷开始使用时间2014-11-27 23:59
                    $data2['expiration_time'] = 1417244400; //结束时间2014-11-29 14:30
                    $data2['status'] = 3;//状态3代表是此活动优惠码
                    M('favorable')->add($data2);
                    $data['coupon_code'] = $data2['coupon_code'];
                }

                $title = str_replace('{$from_name}', $data['from_name'], $email_template['title']);
                $contents = str_replace(
                    array('{$from_name}', '{$to_name}', '{$msg}', '{$amount}', '{$gift_code}', '{$coupon_code}'),
                    array($data['from_name'], $data['to_name'], $data['msg'], currency($data['amount']), $data['gift_code'], $data['coupon_code']),
                    $email_template['content']
                );

                $mailInstance->sendMail_direct($data['recipient_email'], $title, $contents);
                $data['email_send_time'] = time();

                $title2 = str_replace('{$to_name}', $data['to_name'], $coupon_template['title']);
                $contents2 = str_replace(array('{$from_name}', '{$to_name}', '{$recipient_email}'),
                    array($data['from_name'], $data['to_name'], $data['recipient_email']),
                    $coupon_template['content']);

                $mailInstance->sendMail_direct($attr['user_email'], $title2, $contents2);//发送通知邮件给购买者
                M('giftcard')->add($data);
            }

            //更新giftcode到订单商品属性
            $attr['giftcode'] = implode(",", $gift_code_arr);
            $info_v['attr'] = serialize($attr);
            M('orders_items')->where("id=" . $v['id'])->save($info_v);
        }
    }

    public static function invite_fanxian($order_id)
    {
        $order_info = M('orders')->find($order_id);
        if ($order_info['order_amount'] < 250) {
            return false; //订单价格没有达到可以返现的条件
        }

        if ($order_info['coupon_code'] && $order_info['user_id']) {//游客使用优惠码购物，邀请人就不能得到返现
            $invite_db = M('email_invite_items');
            $info = $invite_db->where("invite_coupon_code = '" . $order_info['coupon_code'] . "'")->find();//验证优惠码是不是好友邀请活动的优惠码
            //var_dump($invite_db->getLastSql());
            if (!$info) {
                // '该优惠码不属于被邀请人或者不存在相关记录;
                return false;
            }
            // if($info['user_email'] == $info['invited_email']){
            if ($info['user_email'] == $order_info['delivery_email']) {
                // 自己不能返现给自己';
                return false;
            }

            //查看被返现对象是否是注册用户，否则无法返现；
            //先根据用户id查找
            $user_db = M('users');
            if ($info['user_id']) {
                $fanxianren_info = $user_db->where("id = {$info['user_id']}")->find();
            }

            if (!$fanxianren_info) {//用户id查不到，再根据用户邮箱查,参加活动之前可能该用户还没有注册，所以没有存用户id
                $fanxianren_info = $user_db->where("email = '" . $info['user_email'] . "'")->find();
            }

            // var_dump( $user_db->getLastSql());
            if (!$fanxianren_info) {
                //'被返现人 不是注册用户！';
                return false;
            }

            //该邮箱用户是否有返现过给别人，排除多次发送优惠码情况可能出现的问题(因为好友邀请活动并没有对发送邮件次数的限制),可能该用户已经使用过其他优惠码，并返现给别人
            //一个帐户只能返现一次
            $where['fanxian_status'] = 1;
            $where['invited_email'] = $info['invited_email'];
            $is_fanxian = $invite_db->field('id')->where($where)->find();//查找有没有该用户返现过的记录
            if (!$is_fanxian) {//没有返现过，就返现
                $data['id'] = $fanxianren_info['id'];
                $data['user_money'] = $fanxianren_info['user_money'] + 50;
                // var_dump( $invite_db->getLastSql());
                if ($user_db->save($data)) { //'返现成功';
                    //var_dump( $user_db->getLastSql());
                    $fdata['id'] = $info['id'];
                    $fdata['fanxian_status'] = 1;
                    $invite_db->save($fdata);//标记该邮箱用户已经参加活动并返现给其他人了，不能再返现给别人
                    //var_dump( $invite_db->getLastSql());
                    UserModel::log_account_change($info['user_id'], 50, 0, 0, 0, L('refer_a_friend'), UserModel::ACT_SAVING);
                    return true;
                }
            }

        }
    }

    /**
     * 添加产品到订单产品关联表
     * @param int $order_id 订单ID号
     * @param array $post post数据
     * @return boolean
     */
    public static function insert_order_items($order_id, $post)
    {
        $attr = unserialize($post['attr']);
        if ($attr) {
            //定制
            if ($post['custom_type']) {
                $attrList = array();
                foreach ($attr as $attrv) {
                    $attr2 = explode(':', $attrv);
                    $attrList[] = array(
                        'attr_id' => $attr2[0],
                        'attr_name' => $attr2[1],
                        'product_attr_id' => $attr2[2],
                        'attr_value' => $attr2[3],
                        'attr_value_id' => $attr2[4],
                    );
                }
                $attributeArray = $attrList;
            } //普通
            else {
                $attributeList = AttributeModel::get_product_attribute_List($attr);
                if ($attributeList) {
                    foreach ($attributeList as $attribute) {
                        $attributeArray[$attribute['attr_name']] = $attribute['attr_value'];
                    }
                }
            }
        }
        $order_items_db = D('orders_items');
        $pay_price = isset($post['pay_price']) ? floatval($post['pay_price']) : $post['sell_price'];
        $data = array(
            'order_id' => $order_id,
            'product_id' => $post['product_id'],
            'product_sn' => $post['product_sn'],
            'product_name' => $post['product_name'],
            'sell_price' => $post['sell_price'],
            'qty' => $post['qty'],
            'weight' => $post['weight'],
            'total_weight' => $post['qty'] * $post['weight'],
            'pay_price' => $pay_price,
            'total_amount' => $pay_price * $post['qty'] + $post['pants_price'] * $post['pants_qty'],
            'custom_type' => $post['custom_type'],
            'chima' => $post['chima'],
            'car_type' => $post['car_type'],
            'designer_id' => $post['designer_id'],
            'measure_id' => $post['measure_id'],
            'attr' => (isset($attributeArray) && $attributeArray) ? serialize($attributeArray) : $attr,
            'special_request_1' => $post['special_request_1'],
            'pants_price' => $post['pants_price'],
            'pants_qty' => $post['pants_qty'],
        );
        $lastId = $order_items_db->add($data);
        if ($lastId) {
            //更新产品库存
            ProductModel::update_product_stock($post['product_id'], (-1) * $post['qty']);
        }
        return $lastId;
    }


    /**
     * 更新订单价格
     * @param int $order_id 订单ID号
     * @return vod
     */
    public static function update_order_prices($order_id)
    {
        $orderInfo = self::get_order_info($order_id);
        if (!$orderInfo) return false;

        $order_items_db = D('orders_items');

        //获取产品总价格
        $product_amount = 0;
        $total_weight = 0;
        $productList = $order_items_db->field('total_weight,total_amount')->where('order_id=' . $order_id)->select();
        if ($productList) {
            foreach ($productList as $product) {
                $product_amount += $product['total_amount'];
                $total_weight += $product['total_weight'];
            }
        }

        $order_db02 = D('orders');
        $productInfo = $order_db02->field('order_status,payment_status')->where('id=' . $order_id)->find();

        //获取配送费用
        $shipping_fee = ShippingModel::get_shipping_fee($orderInfo['shipping_method'], $orderInfo['delivery_cid'], $product_amount, $total_weight, $order_id);
        //获取支付费用
        //$payment_fee = PaymentModel::get_paymeent_fee($orderInfo['payment_method'], $product_amount);
        $payment_fee = $orderInfo['payment_fee'];
        //应付金额 = 产品价格+支付费用+配送费用-余额支付-积分支付-优惠金额
        $pay_amount = $product_amount + $payment_fee + $shipping_fee - $orderInfo['surplus_money'] - $orderInfo['integral_money'] - $orderInfo['hongbao_money'] - $orderInfo['coupon_money'] - $orderInfo['discount_amount'];

        //获取支付价格
        if ($pay_amount == 0) {
            $payment_status = self::PAY_PAYED;
            $order_status = self::ORDER_CONFIRMED;
        } //TODO支付的费用多于订单费用要退款
        elseif ($pay_amount < 0) {
            $order_status = self::ORDER_CONFIRMED;
            $payment_status = self::PAY_PAYED;
            //退款
            if ($orderInfo['user_id']) {
                UserModel::log_account_change($orderInfo['user_id'], $pay_amount, 0, 0, 0, L('_ORDER_REFUND_') . ' ' . L('_THE_ORDER_NUMBER_IS_') . ' ' . $orderInfo['order_sn'], UserModel::ACT_REFUND);
            }
        } elseif ($pay_amount > 0) {
            $order_status = $productInfo['order_status'];
            $payment_status = $productInfo['payment_status'];
        }

        $data = array(
            'product_amount' => $product_amount,
            'payment_fee' => $payment_fee,
            'shipping_fee' => $shipping_fee,
            'order_amount' => $product_amount + $shipping_fee + $payment_fee,
            'pay_amount' => $pay_amount,
            'payment_status' => $payment_status,
        );
        if (isset($order_status)) {
            $data['order_status'] = $order_status;
        }

        $order_db = D('orders');
        $order_db->where('id=' . $order_id)->save($data);
//  	echo $order_db->getLastSql();exit;
        //减去会员支付使用的积分
        if ($orderInfo['user_id'] && $orderInfo['integral']) {
            $user_db = D('users');
            UserModel::log_account_change($orderInfo['user_id'], 0, 0, 0, (-1) * $orderInfo['integral'], L('_ORDER_USE_INTEGRAL_PAYMENT_') . ' ' . L('_THE_ORDER_NUMBER_IS_') . ' ' . $orderInfo['order_sn'], UserModel::ACT_REFUND);
        }
        //如果已经支付赠送积分
        if ($payment_status == self::PAY_PAYED) {
            self::send_order_points($order_id);
            return $payment_status;
        }
    }

    /**
     * 更新订单价格（预售）
     * @param int $order_id 订单ID号
     * @return vod
     */
    public static function update_order_prices02($order_id)
    {
        $orderInfo = self::get_order_info($order_id);
        if (!$orderInfo) return false;

        $order_items_db = D('orders_items');

        //获取产品总价格
        $product_amount = 0;
        $total_weight = 0;
        $productList = $order_items_db->field('total_weight,total_amount')->where('order_id=' . $order_id)->select();
        if ($productList) {
            foreach ($productList as $product) {
                $product_amount += $product['total_amount'];
                $total_weight += $product['total_weight'];
            }
        }
        //获取配送费用
        $shipping_fee = ShippingModel::get_shipping_fee($orderInfo['shipping_method'], $orderInfo['delivery_cid'], $product_amount, $total_weight, $order_id);

        //获取支付费用
        //$payment_fee = PaymentModel::getPaymeentFee($orderInfo['payment_method'], $product_amount);
        $payment_fee = $orderInfo['payment_fee'];

        //应付金额 = 预付定金
        $pay_amount = $orderInfo['product_dingjin'] - $orderInfo['surplus_money'];

        //获取支付价格
        if ($pay_amount == 0) {
            $payment_status = self::PAY_FOUR_REFUND;
            $order_status = self::ORDER_CONFIRMED;
        } //TODO支付的费用多于订单费用要退款
        elseif ($pay_amount < 0) {
            $order_status = self::ORDER_CONFIRMED;
            $payment_status = self::PAY_FOUR_REFUND;
            //退款
            if ($orderInfo['user_id']) {
                UserModel::log_account_change($orderInfo['user_id'], $pay_amount, 0, 0, 0, L('_ORDER_REFUND_') . ' ' . L('_THE_ORDER_NUMBER_IS_') . ' ' . $orderInfo['order_sn'], UserModel::ACT_REFUND);
            }
        }

        $data = array(
            'product_amount' => $product_amount,
            'payment_fee' => $payment_fee,
            'shipping_fee' => $shipping_fee,
            'order_amount' => $product_amount + $shipping_fee + $payment_fee,
            'pay_amount' => $pay_amount,
            'payment_status' => $payment_status,
        );
        if (isset($order_status)) {
            $data['order_status'] = $order_status;
        }

        $order_db = D('orders');
        $order_db->where('id=' . $order_id)->save($data);
//  	echo $order_db->getLastSql();exit;
        //减去会员支付使用的积分
        if ($orderInfo['user_id'] && $orderInfo['integral']) {
            $user_db = D('users');
            UserModel::log_account_change($orderInfo['user_id'], 0, 0, 0, (-1) * $orderInfo['integral'], L('_ORDER_REFUND_') . ' ' . L('_THE_ORDER_NUMBER_IS_') . ' ' . $orderInfo['order_sn'], UserModel::ACT_REFUND);
        }
        //如果已经支付赠送积分
        if ($payment_status == self::PAY_PAYED) {
            self::send_order_points($order_id);
            return $payment_status;
        }
    }

    /**
     * 获取订单积分
     * @param int $order_id 订单号
     */
    public static function send_order_points($order_id)
    {
        $orderInfo = self::get_order_info($order_id);
        if (!$orderInfo || $orderInfo['user_id'] == 0) {
            return false;
        }
        $orders_items_db = D('orders_items');
        $orders_items_db->field('orders_items.qty,product.sell_price,product.rank_integral,product.integral');
        $orders_items_db->join('product ON product.id=orders_items.product_id');
        $orders_items_db->where(array('orders_items.order_id' => $order_id));
        $itemsList = $orders_items_db->select();
        if ($itemsList) {
            $total_rank_integral = 0;
            $total_integral = 0;
            foreach ($itemsList as $item) {
                $rank_integral = $item['rank_integral'] == -1 ? $item['sell_price'] : intval($item['rank_integral']);
                $integral = $item['integral'] == -1 ? $item['sell_price'] : intval($item['integral']);
                $total_rank_integral += $item['qty'] * $rank_integral;
                $total_integral += $item['qty'] * $integral;
            }
            UserModel::log_account_change($orderInfo['user_id'], 0, 0, $total_rank_integral, $total_integral, L('_PAYMENT_SUCCESS_') . ' ' . L('_THE_ORDER_NUMBER_IS_') . ' ' . $orderInfo['order_sn'], UserModel::ACT_PAY);

            $order_db = D('orders');
            $data['pay_integral'] = $total_integral;
            $order_db->where('id=' . $order_id)->save($data);
        }
    }

    /**
     * 全额退订单积分并退款
     * @param int $order_id 订单号
     */
    public static function returned_order_all_points($order_id)
    {
        $orderInfo = self::get_order_info($order_id);
        if (!$orderInfo) {
            return false;
        }
        $orders_items_db = D('orders_items');
        $orders_items_db->field('orders_items.qty,orders_items.product_id,product.sell_price,product.rank_integral,product.integral');
        $orders_items_db->join('product ON product.id=orders_items.product_id');
        $orders_items_db->where(array('orders_items.order_id' => $order_id));
        $itemsList = $orders_items_db->select();
        if ($itemsList) {
            $total_rank_integral = 0;
            $total_integral = 0;
            foreach ($itemsList as $item) {
                $rank_integral = $item['rank_integral'] == -1 ? $item['sell_price'] : intval($item['rank_integral']);
                $integral = $item['integral'] == -1 ? $item['sell_price'] : intval($item['integral']);
                $total_rank_integral += $item['qty'] * $rank_integral;
                $total_integral += $item['qty'] * $integral;
                //退库存
                ProductModel::update_product_stock($item['product_id'], (-1) * $item['qty']);
            }
            //退款退积分
            UserModel::log_account_change($orderInfo['user_id'], $orderInfo['pay_amount'], null, (-1) * $total_rank_integral, (-1) * $total_integral, L('_ORDER_REFUND_') . ' ' . L('order number : ') . $orderInfo['order_sn'], UserModel::ACT_REFUND);
            //退款记录
            $data = array(
                'user_id' => $orderInfo['user_id'] ? $orderInfo['user_id'] : 0,
                'user_name' => $user['username'],
                'order_id' => $orderInfo['id'],
                'order_sn' => $orderInfo['order_sn'],
                'return_amount' => $total_amount,
                'admin_user' => $user['username'],
                'admin_note' => L('_ORDER_REFUND_') . ' ' . L('_THE_ORDER_NUMBER_IS_') . ' ' . $orderInfo['order_sn'] . '; ' . L('_PAYMENT_METHOD_') . '：' . $orderInfo['payment_method_name'],
                'status' => 0,
            );
            if ($orderInfo['user_id']) {
                $data['admin_note'] .= '<br/>' . L('_ALREADY_BACK_INTO_BALANCE_');
                $data['status'] = 2;
                $data['user_name'] = $user['username'] ? $user['username'] : 'Anonymous';
            } else {
                $data['user_name'] = 'Anonymous';
            }

            //退款邮件
            if ($orderInfo['delivery_email']) {
                $email_template = UserModel::get_email_template_info('payReturnEmail', $orderInfo['language_id']);
                //发邮件
                if ($email_template) {
                    $mailInstance = new EmailModel();
                    $content = str_replace('{$user_name}', $orderInfo['delivery_first_name'] . ' ' . $orderInfo['delivery_last_name'], $email_template['content']);
                    $content = str_replace('{$admin_note}', $data['admin_note'], $content);
                    $title = str_replace('{$order_sn}', $orderInfo['order_sn'], $email_template['title']);
                    $content = $mailInstance->replaceMail($content);
                    $title = $mailInstance->replaceMail($title);
                    $mailInstance->sendMail($orderInfo['delivery_email'], $title, $content);
                }
            }
            self::update_pay_return_log($data);
        }
    }

    /**
     * 获取每个商品的已发货总数
     * @param int $order_items_id 订单商品详细ID
     * @param int $ordery_delivery_id 发货单ID
     */
    public static function get_delivery_send_number($order_items_id, $ordery_delivery_id = 0)
    {
        $order_delivery_product_db = D('orders_delivery_product');
        $where['orders_items_id'] = $order_items_id;
        if ($ordery_delivery_id) {
            $where['orders_delivery_id'] = $ordery_delivery_id;
        } else {
            $where['orders_delivery.status'] = 2; //已发
        }
        $order_delivery_product_db->join('orders_delivery ON orders_delivery.id=orders_delivery_product.orders_delivery_id');
        $order_delivery_product_db->where($where);
        $send_number = $order_delivery_product_db->getField('SUM(send_number) AS count');
        return intval($send_number);
    }

    /**
     * 订单部分退积分退款
     * @param int $order_id 订单号
     */
    public static function returned_part_order_points($order_id)
    {
        global $user;
        $orderInfo = self::get_order_info($order_id);
        if (!$orderInfo) {
            return false;
        }
        //如果没有发过货全退
        $orders_delivery_db = D('orders_delivery');
        $count = $orders_delivery_db->where(array('order_id' => $order_id, 'status' => 2))->count();
        if (!$count) {
            self::returned_order_all_points($order_id);
            return true;
        }

        $orders_items_db = D('orders_items');
        $orders_items_db->field('orders_items.id,orders_items.qty,orders_items.product_id,orders_items.pay_price,product.sell_price,product.rank_integral,product.integral');
        $orders_items_db->join('product ON product.id=orders_items.product_id');
        $orders_items_db->where(array('orders_items.order_id' => $order_id));
        $itemsList = $orders_items_db->select();
        if ($itemsList) {
            $total_rank_integral = 0;
            $total_integral = 0;
            $total_amount = 0;
            foreach ($itemsList as $item) {
                $send_number = self::get_delivery_send_number($item['id']);
                if ($item['qty'] == $send_number) continue;
                $qty = $item['qty'] = $send_number;

                $rank_integral = $item['rank_integral'] == -1 ? $item['sell_price'] : intval($item['rank_integral']);
                $integral = $item['integral'] == -1 ? $item['sell_price'] : intval($item['integral']);
                $total_rank_integral += $qty * $rank_integral;
                $total_integral += $qty * $integral;
                $total_amount += $qty * $item['pay_price'];
                //退库存
                ProductModel::update_product_stock($item['product_id'], (-1) * $qty);
            }
            //退款退积分
            UserModel::log_account_change($orderInfo['user_id'], $total_amount, null, (-1) * $total_rank_integral, (-1) * $total_integral, L('_ORDER_REFUND_') . ' ' . L('order number : ') . $orderInfo['order_sn'], UserModel::ACT_REFUND);

            //退款记录
            $data = array(
                'user_id' => $orderInfo['user_id'] ? $orderInfo['user_id'] : 0,
                'user_name' => $user['username'],
                'order_id' => $orderInfo['id'],
                'order_sn' => $orderInfo['order_sn'],
                'return_amount' => $total_amount,
                'admin_user' => $user['username'],
                'admin_note' => L('_ORDER_REFUND_') . ' ' . L('_THE_ORDER_NUMBER_IS_') . ' ' . $orderInfo['order_sn'] . '; ' . L('_PAYMENT_METHOD_') . '：' . $orderInfo['payment_method_name'],
                'status' => 0,
            );
            if ($orderInfo['user_id']) {
                $data['admin_note'] .= '<br/>' . L('_ALREADY_BACK_INTO_BALANCE_');
                $data['status'] = 2;
                $data['user_name'] = $user['username'] ? $user['username'] : 'Anonymous';
            } else {
                $data['user_name'] = 'Anonymous';
            }

            //退款邮件
            if ($orderInfo['delivery_email']) {
                $email_template = UserModel::get_email_template_info('payReturnEmail', $orderInfo['language_id']);
                //发邮件
                if ($email_template) {
                    $mailInstance = new EmailModel();
                    $content = str_replace('{$user_name}', $orderInfo['delivery_first_name'] . ' ' . $orderInfo['delivery_last_name'], $email_template['content']);
                    $content = str_replace('{$admin_note}', $data['admin_note'], $content);
                    $title = str_replace('{$order_sn}', $orderInfo['order_sn'], $email_template['title']);
                    $content = $mailInstance->replaceMail($content);
                    $title = $mailInstance->replaceMail($title);
                    $mailInstance->sendMail($orderInfo['delivery_email'], $title, $content);
                }
            }
            self::update_pay_return_log($data);

        }
    }

    /**
     * 订单取消退回支付使用的积分和余额
     * @param int $order_id 订单ID
     */
    public static function returned_order_surplus_and_points($order_id)
    {
        $order_db = D('orders');
        $orderInfo = $order_db->field('user_id,id,surplus_money,integral,order_sn')->find($order_id);
        if ($orderInfo['user_id']) {
            UserModel::log_account_change($orderInfo['user_id'], $orderInfo['surplus_money'], null, null, $orderInfo['integral'], L('The order cancal') . ' ' . L('order number : ') . $orderInfo['order_sn'], UserModel::ACT_REFUND);
        }
        $data = array(
            'surplus_money' => 0,
            'integral' => 0,
            'integral_money' => 0,
            'payment_status' => OrderModel::PAY_UNPAYED,
        );
        $order_db->where(array('id' => $order_id))->save($data);
    }

    /**
     * 更新退款记录
     * @param array $post post数组
     * @param int $pid 记录ID
     */
    public static function update_pay_return_log($post, $pid = null)
    {
        $pay_return_db = D('orders_pay_return');
        if ($post['return_amount'] == 0 || $post['return_amount'] == '0.00') {
            return false;
        }
        $data = array(
            'return_amount' => floatval($post['return_amount']),
            'admin_note' => trim($post['admin_note']),
            'admin_user' => $post['admin_user'] ? $post['admin_user'] : 'system',
            'end_time' => time(),
            'status' => intval($post['status']),
        );

        if (!$pid) {
            $data['user_id'] = $post['user_id'] ? $post['user_id'] : null;
            $data['user_name'] = $post['user_name'] ? $post['user_name'] : null;
            $data['order_id'] = $post['order_id'] ? $post['order_id'] : null;
            $data['order_sn'] = $post['order_sn'] ? $post['order_sn'] : null;
            $data['add_time'] = time();
            $pid = $pay_return_db->add($data);
        } else {
            $pay_return_db->where('id=' . $pid)->save($data);
        }
        return $pid;
    }

    /**
     * 处理订单日志
     * @param Array $post 提交字段
     * @return boolean
     */
    public static function insert_orders_log($post)
    {
        if (!isset($post['order_id']) || intval($post['order_id']) == 0) {
            return false;
        }
        $data = array(
            'order_id' => isset($post['order_id']) ? intval($post['order_id']) : 0,
            'order_status' => isset($post['order_status']) ? $post['order_status'] : 0,
            'payment_status' => isset($post['payment_status']) ? $post['payment_status'] : 0,
            'shipping_status' => isset($post['shipping_status']) ? $post['shipping_status'] : 0,
            'action_notice' => $post['action_notice'] ? trim($post['action_notice']) : null,
            'action_name' => $post['action_name'] ? trim($post['action_name']) : null,
            'pro_type' => $post['pro_type'] ? trim($post['pro_type']) : 0,
            'type' => $post['type'] ? trim($post['type']) : 0,
            'action_time' => time(),
        );

        $order_log_db = D('orders_log');
        $lastId = $order_log_db->add($data);
        return (boolean)$lastId;
    }


    /**
     * 生成订单号
     * @return string
     */
    public static function get_order_sn()
    {
        global $user;
        /* 选择一个随机的方案 */
        mt_srand((double)microtime() * 1000000);
        $orderpr = C('order_prefix');
        //合作伙伴订单首字母P开头
        if (isset($user['id']) && $user['id'] > 0 && $user['is_partner'] == 1) {
            $orderpr = 'P';
        }
        return $orderpr . date('ymd') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
//  	$order_db = D('orders');
//  	$number = '';
//    $orderpr = C('order_prefix');
//    $order_info = $order_db->field('order_sn')->order('id DESC')->find();
//    $num = $order_info['order_sn'];
//    $today = date('Ymd',time());
//    $number = $orderpr . $today . sprintf('%04d', 1);
//    if ($num && (substr($num, -12, 8) == $today)) {
//      $i = intval(substr($num, -4)) + 1;
//      $number = $orderpr . $today . sprintf('%04d', $i);
//    }
//    return $number;
    }

    /**
     * 生成订单令牌
     */
    public static function get_order_token()
    {
        // 标识当前页面唯一性
        if (!isset($_SESSION['ordertoken'])) {
            import('ORG.Util.String');
            $_SESSION['ordertoken'] = String::randString(16);
        }
        return $_SESSION['ordertoken'];
    }

    /**
     * 获取订单的发货单列表
     * @param int $order_id 订单ID号
     * @return Array
     */
    public static function get_delivery_list($order_id)
    {
        $order_delivery_db = D('orders_delivery');
        $deliveryList = $order_delivery_db->where('order_id=' . $order_id)->select();
        if ($deliveryList) {
            foreach ($deliveryList as &$delivery) {
                $delivery['productList'] = self::get_delivery_product_list($order_id, $delivery['id']);
            }
        }
        return $deliveryList;
    }

    /**
     * 获取发货单商品列表
     * @param int $order_id 订单ID号
     * @param int $delivery_id 发货单ID
     * @return Array
     */
    public static function get_delivery_product_list($order_id, $delivery_id)
    {
        //发货商品
        $order_item_db = D('orders_items');
        $order_item_db->field('orders_items.*,product.small_img, odp.send_number');
        $order_item_db->join('product ON product.id = orders_items.product_id');
        $order_item_db->join('orders_delivery_product AS odp ON odp.orders_items_id=orders_items.id');
        $order_item_db->join('orders_delivery AS od ON od.id = odp.orders_delivery_id');
        $order_item_db->where(array('orders_items.order_id' => $order_id, 'od.id' => $delivery_id));
        $productList = $order_item_db->select();
        if ($productList) {
            foreach ($productList as &$product) {
                if ($product['attr']) {
                    $data = unserialize($product['attr']);
                    if ($data) {
                        $attributes = array();
                        if ($product['custom_type']) {
                            foreach ($data as $vk => $val) {
                                $attributes[] = $val['attr_name'] . ':' . $val['attr_value'];
                            }
                        } else {
                            foreach ($data as $vk => $val) {
                                $attributes[] = $vk . ':' . $val;
                            }
                        }
                        $attribute = implode(' , ', $attributes);
                    }
                    $product['attr'] = $attribute;
                }
            }
            unset($product);
        }
        return $productList;
    }


    /**
     * 添加退换货信息
     * @param array $post
     */
    public static function insert_purchase_info($post)
    {
        $orders_purchase_db = D('orders_purchase');
        $data = array(
            'parent_id' => isset($post['parent_id']) ? $post['parent_id'] : 0,
            'user_id' => isset($post['user_id']) ? $post['user_id'] : 0,
            'order_id' => isset($post['order_id']) ? $post['order_id'] : 0,
            'product_id' => isset($post['product_id']) ? $post['product_id'] : 0,
            'orders_items_id' => isset($post['orders_items_id']) ? $post['orders_items_id'] : 0,
            'order_sn' => isset($post['order_sn']) ? $post['order_sn'] : null,
            'product_name' => isset($post['product_name']) ? $post['product_name'] : null,
            'purchase_type' => isset($post['purchase_type']) ? $post['purchase_type'] : 1,
            'number' => isset($post['number']) ? $post['number'] : 1,
            'description' => isset($post['description']) ? trim($post['description']) : null,
            'images' => isset($post['photo_name']) ? rtrim($post['photo_name'], ',') : null,
            'contact_name' => isset($post['contact_name']) ? $post['contact_name'] : null,
            'contact_phone' => isset($post['contact_phone']) ? $post['contact_phone'] : null,
            'contact_email' => isset($post['contact_email']) ? $post['contact_email'] : null,
            'add_time' => time(),
            'status' => intval($post['status']),
        );
        $pid = $orders_purchase_db->add($data);
        return $pid;
    }


    /**
     * 获取产品的购买记录
     * @param int $pid 产品ID
     */
    public static function get_buy_product_history($pid)
    {
        $order_items_db = D('orders_items');
        $order_items_db->field('orders.delivery_first_name,orders.delivery_last_name,orders.delivery_country,orders.delivery_city,orders.delivery_province,orders.start_time,orders_items.qty');
        $order_items_db->join('orders ON orders.id=orders_items.order_id');
        $historyList = $order_items_db->where('product_id=' . $pid)->group('order_id')->select();
        return $historyList;
    }

    /**
     * 获取订单数量
     * @param array $post
     * @return IntlDateFormatter
     */
    public static function get_order_count($post = array())
    {
        $filter = array(
            'order_status' => isset($post['order_status']) ? $post['order_status'] : null,
            'payment_status' => isset($post['payment_status']) ? $post['payment_status'] : null,
            'shipping_status' => isset($post['shipping_status']) ? $post['shipping_status'] : null,
            'order_sn' => isset($post['order_sn']) ? trim($post['order_sn']) : null,
            'user_id' => isset($post['user_id']) ? intval($post['user_id']) : null,
            'address_id' => isset($post['address_id']) ? intval($post['address_id']) : null,
        );

        if ($post['start_time'] && $post['end_time']) {
            $filter['start_time'] = array(array('gt', strtotime($post['start_time'])), array('lt', strtotime($post['end_time'])), 'AND');
        } elseif ($post['start_time']) {
            $filter['start_time'] = array('gt', strtotime($post['start_time']));
        } elseif ($post['end_time']) {
            $filter['start_time'] = array('lt', strtotime($post['end_time']));
        }

        foreach ($filter as $key => $val) {
            if (is_null($val)) {
                unset($filter[$key]);
            }
        }

        $order_db = D('orders');
        $order_db->where($filter);
        $count = $order_db->count();//总记录数
        return $count;
    }

    /**
     * 获取订单数据
     * @param array $post
     * @return IntlDateFormatter
     */
    public static function get_order_field($post = array(), $field)
    {
        $filter = array(
            'order_status' => isset($post['order_status']) ? $post['order_status'] : null,
            'payment_status' => isset($post['payment_status']) ? $post['payment_status'] : null,
            'shipping_status' => isset($post['shipping_status']) ? $post['shipping_status'] : null,
            'order_sn' => isset($post['order_sn']) ? trim($post['order_sn']) : null,
            'user_id' => isset($post['user_id']) ? intval($post['user_id']) : null,
            'address_id' => isset($post['address_id']) ? intval($post['address_id']) : null,
            'payment_time' => isset($post['payment_time']) ? $post['payment_time'] : null,
        );

        if ($post['start_time'] && $post['end_time']) {
            $filter['start_time'] = array(array('gt', strtotime($post['start_time'])), array('lt', strtotime($post['end_time'])), 'AND');
        } elseif ($post['start_time']) {
            $filter['start_time'] = array('gt', strtotime($post['start_time']));
        } elseif ($post['end_time']) {
            $filter['start_time'] = array('lt', strtotime($post['end_time']));
        }

        foreach ($filter as $key => $val) {
            if (is_null($val)) {
                unset($filter[$key]);
            }
        }

        $order_db = D('orders');
        if ($field)
            $order_db->field($field);
        $order_db->where($filter);
        $orderRes = $order_db->find();
        return $orderRes;
    }


    /**
     * 获取产品订单列表及分成
     * @param int $product_id
     */
    public static function get_product_order_sharing($product_id)
    {
        $where = array(
            'os.product_id' => $product_id,
            'orders.order_status' => self::ORDER_COMPLETE,
        );
        $order_sharing_db = D('orders_sharing os');
        $order_sharing_db->field('os.*,oi.attr');
        $order_sharing_db->join('orders_items AS oi ON oi.id=os.orders_items_id');
        $order_sharing_db->join('orders ON oi.order_id = orders.id');
        $order_sharing_db->where($where);
        $sharingList = $order_sharing_db->select();
        if ($sharingList) {
            foreach ($sharingList as &$shar) {
                if ($shar['attr']) {
                    $data = unserialize($shar['attr']);
                    if ($data) {
                        $attributes = array();
                        foreach ($data as $vk => $val) {
                            $attributes[] = $vk . ':' . $val;
                        }
                        $attribute = implode(' , ', $attributes);
                    }
                    $shar['attr'] = $attribute;
                }
            }
        }
//		echo $order_sharing_db->getLastSql();
        return $sharingList;
    }

    /**
     * 获取商品当前这周这周销售的数量
     * @param array $post
     * @return IntlDateFormatter
     */
    public static function get_product_count()
    {
        $order_db = D('orders');
        $order_db->field('sum(orders_items.qty) as number');
        $order_db->join('orders_items ON orders_items.order_id = orders.id');
        $number = $order_db->where('YEARWEEK(date_format(from_unixtime(orders.start_time),"%Y-%m-%d")) = YEARWEEK(now()) AND orders.payment_status=4')->find();

        return $number['number'];
    }

    /**
     * 获取每个商品预订数量
     * @param int $product_id
     */
    public static function get_presell_product_people_count($product_id)
    {
        $order_db = D('orders');
        $order_db->join('orders_items ON orders_items.order_id = orders.id');
        $number = $order_db->where('product_id=' . $product_id . ' AND orders.payment_status=4')->count();
//		echo $order_db->getLastSql();exit;
        return $number ? $number : 0;
    }

    /**
     * 处理订单日志
     * @param Array $post 提交字段
     * @return boolean
     */
    public static function insertOrdersLog($post)
    {
        if (!isset($post['order_id']) || intval($post['order_id']) == 0) {
            return false;
        }
        $data = array(
            'order_id' => isset($post['order_id']) ? intval($post['order_id']) : 0,
            'order_status' => isset($post['order_status']) ? $post['order_status'] : 0,
            'payment_status' => isset($post['payment_status']) ? $post['payment_status'] : 0,
            'shipping_status' => isset($post['shipping_status']) ? $post['shipping_status'] : 0,
            'action_notice' => $post['action_notice'] ? trim($post['action_notice']) : null,
            'action_name' => $post['action_name'] ? trim($post['action_name']) : null,
            'action_time' => time(),
        );

        $order_log_db = D('orders_log');
        $lastId = $order_log_db->add($data);
        return (boolean)$lastId;
    }

    /**
     * 处理订单日志
     * @param Array $orderInfo 订单数据
     * @param Array $paymentInfo 支付返回数据
     * @return
     */
    public static function payment_insertOrdersLog($orderInfo, $paymentInfo)
    {
        //添加订单日志
        if ($orderInfo && $paymentInfo['paymentId']) {
            $logData = array(
                'order_id' => $orderInfo['id'],
                'order_status' => $orderInfo['order_status'],
                'payment_status' => $orderInfo['payment_status'],
                'shipping_status' => $orderInfo['shipping_status'],
                'action_notice' => '用户支付失败,订单流水号:' . $paymentInfo['paymentId'] . ' msg:' . $paymentInfo['returnMsg'],
                'action_name' => 'admin',
            );
            $order_log_db = D('orders_log');
            $result = $order_log_db->where($logData)->count();
            if ($result > 0) {
                return;
            }
            self::insertOrdersLog($logData);
        }
    }

    /**
     * 根据订单号获取订单id
     * @param str $order_sn
     * @return int $order_id
     */
    public static function get_orderId_by_orderSn($order_sn)
    {
        $orders_db = D('orders');
        $order_id = $orders_db->where(array('order_sn' => $order_sn))->getField('id');
        return $order_id;
    }

    /**
     * 查询订单中是否有商品已经下架
     * @param str $order_id
     * @return array 放回已下架商品数据
     */
    public static function get_order_product_isdown($order_id)
    {
        $orders_items_db = D('orders_items');
        $where = array(
            'order_id' => $order_id,
        );
        $pidRes = $orders_items_db->field('product_id')->where($where)->select();

        $pidArr = array();
        foreach ($pidRes as $key => $val) {
            $display = D('product')->where(array('id' => $val['product_id']))->getField('display');
            if (in_array($display, array(0, 2))) {
                $pidArr[] = $val['product_id'];
            }
        }
        return $pidArr;
    }
    /**
     * 设置保存修改身型数据
     * @param int $measure_id 身型id
     * @param int $order_item_id order_item表的id
     * @param varche $data 序列化的数据
     * @return boolean
     */
    public static function set_size_measure($measure_id, $order_item_id, $data)
    {

        $data = serialize($data);
        $addData = array(
            'measure_id' => $measure_id,
            'order_item_id' => $order_item_id,
        );

        $size_measure = D('size_measure');
        $res = self::isset_size_measure($measure_id, $order_item_id);
        if ($res) {
            $res = $size_measure->where($addData)->save(array('data' => $data, 'time' => time()));
            return (boolean)$res;
        }

        $addData['data'] = $data;
        $addData['time'] = time();
        $res = $size_measure->add($addData);
        return (boolean)$res;
    }

    /**
     * 获取保存身型数据的id
     * @param int $measure_id 身型id
     * @param int $order_item_id order_item表的id
     * @return boolean
     */
    public static function isset_size_measure($measure_id, $order_item_id)
    {

        $size_measure = D('size_measure');
        $where = array(
            'measure_id' => $measure_id,
            'order_item_id' => $order_item_id,
        );
        $res = $size_measure->where($where)->getField('id');

        return (boolean)$res;


    }

    //获取用户的商品类型
    public static function orderPrintFigure($order_item_id)
    {
        $order_item_db = D('orders_items');
        $productList = $order_item_db->where(array('id' => $order_item_id))->find();
        //dump($productList);exit;
        if ($productList) {
            //获取商品的中文名称
            if ($productList['product_name']) {
                $where_name = array('product_id' => $productList['product_id'], 'language_id' => 6);
                $product_items = D('product_items')->where($where_name)->getField('name');
            }
            $buttonArr = array(); //纽扣数据
            //默认纽扣
            $product = ProductModel::getProductInfo($productList['product_id']);
            //礼服特殊处理
            if ( $product['model_id'] == 23 ){
                $cat_parentid = CategoryModel::get_category_parentid($product['catid']);
                if ( $product['catid'] == 2061 || $cat_parentid == 2061 ) {
                    $product['model_id'] = 18;
                } else {
                    $product['model_id'] = 2;
                }
            }
            if ( $product['model_id'] == 1 ) { //单西
                $buttonArr['24L'] = 3 + 8; //袖叉
                $buttonArr['32L'] = 1;
            } else if ( $product['model_id'] == 2 ) { //两件套
                $buttonArr['24L'] = 3 + 8; //袖叉
                $buttonArr['32L'] = 1;
            } else if ( $product['model_id'] == 14 ) { //衬衫
                $buttonArr['18L'] = 1;
                $buttonArr['14L'] = 1;
            } else if ( $product['model_id'] == 18 ) { //三件套
                $buttonArr['24L'] = 3 + 8; //袖叉
                $buttonArr['32L'] = 1;
            } else if ( $product['model_id'] == 20 ) { //马甲
                $buttonArr['24L'] = 1;
            } else if ( $product['model_id'] == 21 ) { //裤子
                $buttonArr['24L'] = 1;
            } else if ( $product['model_id'] == 22 ) { //大衣

            }

            if ($productList['attr']) {
                $data = unserialize($productList['attr']);
                if ($data) {
                    $attributes = array();
                    if ($productList['custom_type']) {
                        foreach ($data as $vk => $val) {
                            $attribute_values = D('attribute_values')->field('attr_img,attr_img2,button_type,button_qty')
                                ->where(array('id'=>$val['attr_value_id']))->find();
                            //合计纽扣 （真假袖叉 已提出来单独处理了)
                            if ( $attribute_values['button_type'] && !in_array($val['attr_value_id'], array(136,342,210)) ) {
                                $button_type = $attribute_values['button_type'];
                                if( $buttonArr[$button_type] ) {
                                    $buttonArr[$button_type] += intval($attribute_values['button_qty']);
                                }else{
                                    $buttonArr[$button_type] = intval($attribute_values['button_qty']);
                                }
                            }
                            //衬衫门襟 TS001 TS002 TS003 为18L金属扣 数量4
                            if( in_array($val['attr_value_id'], array(827, 828, 829)) ) {
                                $buttonArr['18Ljsk'] = 4;
                            }
                            //单西两件套三件套 如果有圆角袖叉,
                            if( in_array($val['attr_value_id'], array(762,765,761)) ) {
                                $buttonArr['24L'] -= 8;
                            }

                            //获取定制选项中文名
                            $where_attr = array('attribute_id' => $val["attr_id"],
                                'language_id' => 6);
                            $cn_attr_name = D('attribute_items')->where($where_attr)->getField('name');
                            if (in_array($val["attr_id"], array(54, 70, 112, 134))) {
                                if ($val["attr_value_id"]) {
                                    //获取定制选项值在中文名
                                    $where_attr_val = array('att_value_id' => $val["attr_value_id"],
                                        'language_id' => 6);
                                    $cn_attr_value_name = D('attribute_values_items')->where($where_attr_val)->getField('attr_value');
                                } else {
                                    $cn_attr_value_name = $val['attr_value'];
                                }
                                $attributes[] = $val["attr_id"] . ':' . $cn_attr_value_name;
                                $attributes_more_array[$val["attr_value_id"]]['cn_attr_value_name'] = '有';
                            } else {
                                if ($val["attr_value_id"]) {
                                    //获取定制选项值在中文名
                                    $where_attr_val = array('att_value_id' => $val["attr_value_id"],
                                        'language_id' => 6);
                                    $cn_attr_value_name = D('attribute_values_items')->where($where_attr_val)->getField('attr_value');
                                } else {
                                    $cn_attr_value_name = $val['attr_value'];
                                }
                                $attributes[] = $val["attr_id"] . ':' . $cn_attr_value_name;
                                $attributes_array[$val["attr_id"]] = array('cn_name' => $cn_attr_name, 'cn_attr_value_name' => $cn_attr_value_name, 'attr_value_id' => $val["attr_value_id"], 'attr_img' =>$attribute_values['attr_img'], 'attr_img2' =>$attribute_values['attr_img2'] );
                            }
                        }

                    } else {
                        foreach ($data as $vk => $val) {
                            $attributes[] = $vk . ':' . $val;
                        }
                    }
                    $attribute = implode(' , ', $attributes);
                }
                $productList['attr'] = $attribute;
                $productList['attr_array'] = $attributes_array;
                $productList['attributes_more_array'] = $attributes_more_array;
                $productList['product_name'] = $product_items;
                $productList['buttonArr'] = $buttonArr;
            }

        }
        return $productList;
    }

}